package org.academic.texteditor.gui.component.toolbar;

import java.awt.Component;
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JToolBar;

import org.academic.texteditor.gui.component.listener.DropPasteTextListener;
import org.academic.texteditor.gui.plugin.Plugin;
import org.academic.texteditor.helper.MessageHelper;

public class ToolBarFactory {

	private static final MessageHelper msg = MessageHelper.getInstance();
	
	private ToolBarFactory() {
		
	}
	
	public static JToolBar getMain() {
		final String toolBarName = "main";
		
		ToolBarManager toolBarManager = ToolBarManager.getInstance();
		JToolBar mainToolBar = toolBarManager.getToolBar(toolBarName);
		
		if (mainToolBar != null) {
			return mainToolBar;
		}
		
		mainToolBar = new JToolBar(toolBarName);
		mainToolBar.setFloatable(false);
		
		mainToolBar.addSeparator();
		
		toolBarManager.addToolBar(mainToolBar);
		
		return mainToolBar;
	}

	public static JToolBar getClipBoard() {
		final String toolBarName = "clipboard";
		
		ToolBarManager toolBarManager = ToolBarManager.getInstance();
		JToolBar clipBoardToolBar = toolBarManager.getToolBar(toolBarName);
		
		if (clipBoardToolBar != null) {
			return clipBoardToolBar;
		}
		
		clipBoardToolBar = new JToolBar(toolBarName, JToolBar.VERTICAL);
		clipBoardToolBar.setFloatable(true);
		clipBoardToolBar.addSeparator();
		clipBoardToolBar.setDropTarget(new DropTarget(clipBoardToolBar, new DropPasteTextListener()));
		
		toolBarManager.addToolBar(clipBoardToolBar);
		
		return clipBoardToolBar;
	}
	
	public static JButton createButton(JToolBar toolBar, String name, int index, String key, String image, final Plugin plugin) {
		return createButton(toolBar, name, index, key, image, new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				plugin.execute();
			}
		});
	}
	
	public static JButton createButton(JToolBar toolBar, String name, int index, String key, String image, ActionListener actionListener) {
		ClassLoader classLoader = ToolBarFactory.class.getClassLoader();
		
		JToolBarButton action = new JToolBarButton(msg.getMessage(key), new ImageIcon(classLoader.getResource(image)), msg.getMessage(key + ".hint"), '0');
		JButton button = new JButton(action);
		button.setName(name);
		button.setHideActionText(true);
		button.addActionListener(actionListener);
		
		toolBar.add(button, index);
		
		return button;
	}

	public static void removeButton(JToolBar toolBar, String name) {
		if (name == null) {
			return;
		}
		
		Component[] components = toolBar.getComponents();
		for (Component component : components) {
			if (name.equals(component.getName())) {
				component.setVisible(false);
				toolBar.remove(component);
				break;
			}
		}
	}

	
}
